<?php
namespace app\member\model;

use app\BaseModel;
use app\member\info\PermissionMember;
use think\facade\Db;

class Level extends BaseModel
{
    //会员等级表
    protected $name = 'longbing_card_member_level';


    /**
     * @author chenniang
     * @DataTime: 2020-07-15 09:49
     * @功能说明:添加
     */
    public function levelAdd($data){

        $data['status']      = 1;

        $data['create_time'] = time();

        $data['update_time'] = time();

        $goods_id = [];

        $rights   = [];

        $coupon   = [];

        $stored   = [];
        //关联的商品
        if(isset($data['goods_id'])){

            $goods_id = $data['goods_id'];

            unset($data['goods_id']);
        }
        //关联的权益
        if(isset($data['rights'])){

            $rights = $data['rights'];

            unset($data['rights']);
        }
        //关联的优惠券
        if(isset($data['coupon'])){

            $coupon = $data['coupon'];

            unset($data['coupon']);
        }
        //关联储值
        if(isset($data['stored_id'])){

            $stored = $data['stored_id'];

            unset($data['stored_id']);
        }

        $res = $this->insert($data);
        //id
        $level_id = $this->getLastInsID();
        //修改相关数据
        $this->updateSome($goods_id,$rights,$level_id,$data,$coupon,$stored);

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-10 15:13
     * @功能说明:初始化
     */
    public function initLevel($dis){

        //初始化普通会员
        if($dis['type']==0){

            for ($i=1;$i<11;$i++){

                $insert[$i]['uniacid'] = $dis['uniacid'];

                $insert[$i]['status']  = 0;

                $insert[$i]['create_time'] = time();

                $insert[$i]['update_time'] = time();

                $insert[$i]['top'] = $i;
            }

            $this->saveAll($insert);

        }else{
           //初始化puls会员
            $insert['uniacid'] = $dis['uniacid'];

            $insert['status']  = 0;

            $insert['create_time'] = time();

            $insert['update_time'] = time();

            $insert['type'] = 1;

            $insert['top'] = 999;

            $insert['over_time'] = -1;

            $this->insert($insert);
        }
        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:12
     * @功能说明:列表
     */
    public function levelList($dis){

        $data = $this->where($dis)->order('id')->limit(10)->select()->toArray();

        if(empty($data)){
            //初始化
            $this->initLevel($dis);
        }

        $data = $this->where($dis)->order('id')->limit(10)->select()->toArray();

        $member_model = new Member();

        $right_model  = new Rights();

        foreach ($data as &$v){

            $v['rights'] = $right_model->customRights($v['id']);
            //商品折扣
            if($v['discount_switch']==1){

                array_unshift($v['rights'],'商品打折');

            }
            //积分倍率
            if($v['integral_switch']==1){

                array_unshift($v['rights'],'积分倍率'.$v['integral'].'倍');

            }
            //赠送积分
            if($v['send_integral_switch']==1){

                array_unshift($v['rights'],'赠送积分'.$v['send_integral']);

            }
            //赠送优惠券
            if($v['coupon_switch']==1){

                array_unshift($v['rights'],'赠送卡券');

            }

            $growth = $v['growth'];

            $dis   = [];

            $dis[] = ['uniacid','=',$v['uniacid']];

            $dis[] = ['status','=',1];
            //上一个等级
            $top   = $this->where($dis)->where('growth','>',$growth)->order('growth asc')->value('growth');

            if($v['top']!=999){

                if(!empty($top)){

                    $top--;

                    $dis[] = ['growth','between',"$growth,$top"];

                }else{

                    $dis[] = ['growth','>=',"$growth"];
                }
            }

            if($v['top']==999){

                $dis[] = ['over_time','not between',[0,time()]];

            }else{

                $dis[] = ['over_time','between',[0,time()]];

            }
            //会员人数
            $v['member_num'] = $member_model->where($dis)->count();


        }
        return $data;
    }



    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:08
     * @功能说明:详情
     */
    public function levelInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:13
     * @功能说明:删除直播
     */
    public function levelUpdate($dis,$data){

        $data['update_time'] = time();

        $goods_id = [];

        $rights   = [];

        $coupon   = [];

        $stored   = [];
        //关联的商品
        if(isset($data['goods_id'])){

            $goods_id = $data['goods_id'];

            unset($data['goods_id']);
        }
        //关联的权益
        if(isset($data['rights'])){

            $rights = $data['rights'];

            unset($data['rights']);
        }
        //关联的优惠券
        if(isset($data['coupon'])){

            $coupon = $data['coupon'];

            unset($data['coupon']);
        }
        //关联储值
        if(isset($data['stored_id'])){

            $stored = $data['stored_id'];

            unset($data['stored_id']);
        }

        $res = $this->where($dis)->update($data);

        $this->updateSome($goods_id,$rights,$data['id'],$data,$coupon,$stored);

        return $res;

    }


    /**
     * @param $level_id
     * @param $data
     * @功能说明:修改相关数据
     * @author chenniang
     * @DataTime: 2020-07-15 13:40
     */
    public function updateSome($goods_id,$rights,$level_id,$data,$coupon=[],$stored){


        //关联的商品模型
        $good_model = new Goods();

        $good_model->where(['member_id'=>$level_id])->delete();
        //添加关联的商品
        if(!empty($goods_id)){

            array_walk($goods_id, function ($value, $key) use (&$goods_id, $level_id,$data) {

                $goods_id[$key] = [
                    //商品id
                    'goods_id'  => $value,
                    //等级id
                    'member_id' => $level_id,

                    'uniacid'   => $data['uniacid']

                ];

            });
            //添加
            $good_model->saveAll($goods_id);
        }

        //关联的商品模型
        $rights_model = new RightsRelation();

        $rights_model->where(['member_id'=>$level_id])->delete();
        //添加关联的商品
        if(!empty($rights)){

            array_walk($rights, function ($value, $key) use (&$rights, $level_id,$data) {

                $rights[$key] = [
                    //商品id
                    'rights_id' => $value['id'],
                    //等级id
                    'member_id' => $level_id,

                    'uniacid'   => $data['uniacid'],

                    'type'      => $value['type']

                ];

            });
            //添加
            $res = $rights_model->saveAll($rights);
        }
        //优惠券关联模型
        $coupon_model = new Coupon();
        //添加
        $coupon_model->addCoupon($coupon,$level_id,$data);
        //储值关联模型
        $stored_level_model = new StoredLevel();
        //添加储值
        $stored_level_model->addStored($stored,$level_id,$data);

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-16 11:08
     * @功能说明:获取成长值区间
     */
    public function getGrowth($level){

        $data = $this->where(['id'=>$level])->find();

        $dis[]= ['uniacid','=',$data['uniacid']];

        $dis[]= ['growth','>',$data['growth']];

        $top  = $this->where($dis)->order('growth')->find();

        $info['start_growth'] = $data['growth'];

        $info['end_growth']   = !empty($top['growth'])?$top['growth']:0;

        return $info;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-17 13:22
     * @功能说明:会员商品
     */
    public function memberGoods($uniacid,$level_id){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['status','=',1];

        $dis[] = ['is_member','=',1];

        $id = $this->haveSelectGoods($uniacid,$level_id);

        $dis[] = ['id','not in',$id];

        $data  = Db::name('longbing_card_goods')->where($dis)->field('name,id')->select();

        return $data;
    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-09 13:39
     * @功能说明:下拉框
     */
    public function storedSelect($uniacid,$level_id){

        $id = $this->haveSelectStored($uniacid,$level_id);

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['status','=',1];

        $dis[] = ['id','not in',$id];

        $data  =  Db::name('longbing_card_member_stored')->where($dis)->order('top desc,id desc')->select()->toArray();

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-09 14:09
     * @功能说明:已经选了储值
     */

    public function haveSelectStored($uniacid,$level_id){

        $dis[] = ['a.uniacid','=',$uniacid];

        $dis[] = ['b.uniacid','=',$uniacid];

        $dis[] = ['a.member_id','<>',$level_id];

        $store_level_model = new StoredLevel();

        $id = $store_level_model->alias('a')
            ->join('longbing_card_member_level b','a.member_id = b.id')
            ->where($dis)
            ->column('a.stored_id');

        return $id;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-06 15:21
     * @功能说明:已经选了的商品
     */
    public function haveSelectGoods($uniacid,$level_id){

       $dis[] = ['a.uniacid','=',$uniacid];

       $dis[] = ['b.uniacid','=',$uniacid];

       $dis[] = ['a.member_id','<>',$level_id];

       $goods_model = new Goods();

       $id = $goods_model->alias('a')
           ->join('longbing_card_member_level b','a.member_id = b.id')
           ->where($dis)
           ->column('goods_id');

       return $id;
    }


    /**
     * @param $uniacid
     * @功能说明:会员权益
     * @author chenniang
     * @DataTime: 2020-07-22 14:23
     */
    public function memberRights($uniacid,$type = 0){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['status','=',1];

        $dis[] = ['type','=',$type];

        $rights_model = new Rights();

        $data = $rights_model->where($dis)->field('title,id,is_up')->select();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-27 14:14
     * @功能说明:检测状态
     */


    public function checkStatus($id,$status){

        $info = $this->levelInfo(['id'=>$id]);

        if(empty($info)){

            return [ 'code' => 400,'msg' => '未找到' ];

        }
        //开启
        if($status==1){

            $dis[] = ['uniacid','=',$info['uniacid']];

            $dis[] = ['status','=',0];

            $dis[] = ['type','=',0];

            $data  =  $this->where($dis)->order('top')->find();

            if($data['id']!=$id){

                return [ 'code' => 400,'msg' => '请先开启上级或下级'];

            }
        }
        //关闭
        if($status==0){

            $dis[] = ['uniacid','=',$info['uniacid']];

            $dis[] = ['status','=',1];

            $dis[] = ['type','=',0];

            $data  =  $this->where($dis)->order('top desc')->find();

            if($data['id'] != $id){

                return [ 'code' => 400,'msg' => '请先关闭上级或下级'];

            }

        }

        return [ 'code' => 200,'msg' => '' ];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-28 11:23
     * @功能说明:获取等级
     */

    public function getMemberLevel($uniacid,$growth,$type = 0){

        $where = [

            'uniacid' => $uniacid,

            'status'  => 1,

            'type'    => 0
        ];

        if($type==0){

            $data = $this->where($where)->where('growth','>',$growth)->order('growth')->find();

        }else{

            $data = $this->where($where)->where('growth','<=',$growth)->order('growth desc')->find();

        }

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-18 10:14
     * @功能说明:获取plus会员
     */
    public function getPlusLvel($uniacid){


        $where = [

            'uniacid' => $uniacid,

            'status'  => 1,

            'type'    => 1,

            'top'     => 999
        ];

        $data = $this->where($where)->order('growth')->find();


        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-30 09:45
     * @功能说明:获取用户的等级
     */
    public function getUserLevel($uid,$uniacid){

        $member_model = new Member();

        $over_time = $member_model->where(['user_id'=>$uid])->value('over_time');
        //查看是否是plus会员 -1是永久有效
        if($over_time>time()||$over_time==-1){

            $level = $this->getPlusLvel($uniacid);

            if(!empty($level)){

                return $level;
            }

        }

        $growth = $member_model->where(['user_id'=>$uid])->value('growth');

        $growth = !empty($growth)?$growth:0;

        $level  = $this->getMemberLevel($uniacid,$growth,1);


        return $level;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-07 09:39
     * @功能说明:
     */
    public function getAllLevel($uniacid){

        $where = [

            'uniacid' => $uniacid,

            'status'  => 1,

           // 'type'    => 0
        ];

        $son_level = $this->where($where)->column('id');

        return $son_level;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-30 09:53
     * @功能说明:获取下级或者上级的等级
     */
    public function getSonLevel($level,$uniacid,$type=0){

        $where = [

            'uniacid' => $uniacid,

            'status'  => 1,

        ];

        if($type==0){

            $son_level = $this->where($where)->where('top','<',$level['top'])->column('id');

        }else{

            $icon = $level['top']==999?'>=':'>';

            $son_level = $this->where($where)->where('top',$icon,$level['top'])->column('id');

        }

        return $son_level;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-31 10:39
     * @功能说明:升级用户的权益
     */
    public function upUserRights($level,$order){

        $uniacid = $order['uniacid'];

        $user_id = $order['user_id'];

        $integral_model = new Integral();

        $member_model   = new Member();

        $coupon_model   = new Coupon();

        $level_info = $this->levelInfo(['top'=>$level,'uniacid'=>$uniacid]);
        //增加积分记录
        $integral_model->integralUserAdd($user_id,$level_info['send_integral'],$uniacid);
        //加会员的积分
        $dis = [
            'user_id' => $user_id
        ];

        $member_model->incDecGrowth($dis,$level_info['send_integral'],'integral');
        //赠送优惠券
        $coupon_model->insertCoupon($level_info,$order);
        //第一次升级时候 修改创建时间
        $member_model->where(['user_id'=>$order['user_id'],'is_vip'=>0])->update(['create_time'=>time(),'is_vip'=>1]);

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-04 17:22
     * @功能说明:会员成长值
     */
    public function memberGrowth($uniacid){

        $data = $this->where(['uniacid'=>$uniacid,'status'=>1,'type'=>0])->min('growth');

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-18 17:02
     * @功能说明:
     */
    public function upUserRightsEnd($update,$order){

        $user_id = $order['user_id'];

        $uniacid = $order['uniacid'];

        $member_model = new Member();
        //还未升级以前的等级
        $level_start  =  $this->getUserLevel($user_id,$uniacid);
        //如果空就不是会员
        $level_start  = !empty($level_start['top'])?$level_start['top']:0;
        //更新会员信息
        $member_model->where(['user_id'=>$user_id])->update($update);
        //增加后的等级
        $level_end = $this->getUserLevel($user_id,$uniacid);

        $level_end = !empty($level_end['top'])?$level_end['top']:0;
        //普通会员升级礼包
        if($level_end>$level_start){

            $this->upUserRights($level_end,$order);

        }

        return true;

    }












}